import * as THREE from 'three'
import * as DatGUI from 'dat.gui'

import { OrbitControls } from "three/addons/controls/OrbitControls"
export default class ThreeEngine {

    constructor() {
        //实例化场景
        this.initScene()
        //实例化照相机
        this.initCamera()

        //实例化渲染
        //初始化参考坐标系
        this.initAxes()
        this.initRenderer()
        //将场景交给渲染器
        this.initRenderDom()
        this.loopTick()
        this.resize()

    }
    initScene() {
        this.Scene = new THREE.Scene()
    }

    initCamera() {
        this.Camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
        this.Camera.position.z = 5
        this.Camera.position.x = 3
        this.Camera.position.y = 1
    }
    initRenderer() {
        this.Renderer = new THREE.WebGLRenderer()
        this.Renderer.setSize(window.innerWidth, window.innerHeight)
    }
    //渲染3d场景
    initRenderDom() {

        this.Renderer.render(this.Scene, this.Camera)
        document.body.append(this.Renderer.domElement)
    }
    //初始化坐标轴
    initAxes() {
        this.Axes = new THREE.AxesHelper(10)

        this.Scene.add(this.Axes)//加入坐标

    }

    // initGUI
    initGUI() {
        this.GUI = new DatGUI.GUI()
    }
    loopTick() {
        this.control = new OrbitControls(this.Camera, this.Renderer.domElement)
        //每秒刷新60次
        const callBack = () => {
            this.Renderer.render(this.Scene, this.Camera)
            this.control.update()
            requestAnimationFrame(callBack)
        }
        callBack()

    }
    addGeometry(cube) {
        if (cube) {
            this.Scene.add(cube)
        }
    }
    resize() {
        window.addEventListener('resize', () => {
            this.Camera.aspect = window.innerWidth / window.innerHeight
            this.Renderer.setSize(window.innerWidth, window.innerHeight)
            //调用更新
            this.Camera.updateProjectionMatrix()
        })
    }
    // add添加GUI属性的监听
    addGUIProperty(obj, property) {
        if (!this.GUI) this.initGUI()
        this.GUI.add(obj, property)
    }
}